Imports System.Data

Partial Class pages_Seriess_Series : Inherits CPage

#Region "Querystring"
    Public ReadOnly Property SeriesId() As Integer
        Get
            Return CWeb.RequestInt("seriesId")
        End Get
    End Property
    Public ReadOnly Property IsEdit() As Boolean
        Get
            Return SeriesId <> Integer.MinValue
        End Get
    End Property
#End Region

#Region "Members"
    Private m_series As CSeries
#End Region

#Region "Data"
    Public ReadOnly Property [Series]() As CSeries
        Get
            If IsNothing(m_series) Then
                If IsEdit Then
                    m_series = CSeries.Cache.GetById(SeriesId)
                    If IsNothing(m_series) Then CSitemap.RecordNotFound("Series", SeriesId)
                Else
                    m_series = New CSeries
                End If
            End If
            Return m_series
        End Get
    End Property
#End Region

#Region "Navigation"
    Private Sub Refresh()
        Response.Redirect(CSitemap.SeriesEdit(Me.Series.SeriesId))
    End Sub
    Private Sub ReturnToList()
        Response.Redirect(CSitemap.Seriess)
    End Sub
#End Region

#Region "Event Handlers - Page"
    Protected Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Init

        If IsEdit Then
            Me.Title = "Series Details"
        Else
            Me.Title = "Add A New Series"
        End If

        txtData.Visible = IsEdit
        txtFrom.Visible = IsEdit
        txtTo.Visible = IsEdit

        btnDelete.Visible = IsEdit
        If IsEdit Then btnCancel.Text = "Back" Else btnSave.Text = "Create Series"
        btnNew.Visible = IsEdit
    End Sub
    Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack Then Exit Sub

        LoadSeries()
    End Sub
#End Region

#Region "Event Handlers - Form"
    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If Not Me.IsValid() Then Exit Sub
        SaveSeries()
        Refresh()
    End Sub
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        ReturnToList()
    End Sub
    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Me.Series.Delete()

        CSession.SelectedSeriesIds.Remove(m_series.SeriesId)
        CSession.SelectedSeries = Nothing

        ReturnToList()
    End Sub
    Protected Sub btnNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNew.Click
        Response.Redirect(CSitemap.SeriesAdd())
    End Sub
#End Region

#Region "Private - Load/Save"
    Protected Sub LoadSeries()
        With Me.Series
            txtSeriesName.Text = .SeriesName
            txtDp.ValueInt = .SeriesDecimalPlaces

            txtData.NavigateUrl = CSitemap.Datas(SeriesId)
            txtData.Text = CUtilities.CountSummary(Series.Length, "data point")
            If Series.Length > 0 Then
                txtFrom.Text = Series.Datas.MinDate.ToString("d MMM yyyy")
                txtTo.Text = Series.Datas.MaxDate.ToString("d MMM yyyy")
            End If

        End With
    End Sub
    Protected Sub SaveSeries()
        With Me.Series
            .SeriesName = txtSeriesName.Text
            .SeriesDecimalPlaces = txtDp.ValueInt
            .Save()
        End With

        If fileImport.HasFile Then
            If String.IsNullOrEmpty(Series.SeriesName) Then
                Series.SeriesName = IO.Path.GetFileNameWithoutExtension(fileImport.PostedFile.FileName)
                Series.Save()
            End If
            fileImport.FolderPath = CSitemap.DataImports
            Dim fileName As String = fileImport.SaveFile()
            Dim folderPath As String = Server.MapPath(CSitemap.DataImports)
            Dim filePath As String = folderPath & fileName

            Dim hasHeadings As Boolean = True
            Dim ds As DataSet
            Select Case IO.Path.GetExtension(fileName).ToLower
                Case ".csv", ".tab", ".asc"
                    Dim db As CDataSrc = CDataSrc.OleDbFromCsvPath(folderPath)
                    Dim sql As String = String.Concat("SELECT * FROM [", fileName, "]")
                    ds = db.ExecuteDataSet(sql)

                    hasHeadings = True
                    For Each i As DataColumn In ds.Tables(0).Columns
                        hasHeadings = LCase(Trim(i.ColumnName)) = "date"
                    Next

                    If Not hasHeadings Then
                        db = CDataSrc.OleDbFromCsvPath(folderPath, False)
                        ds = db.ExecuteDataSet(sql)
                    End If

                Case ".xls", ".xlsx"
                    Dim db As CDataSrc = CDataSrc.OleDbFromExcelPath(filePath)
                    Dim sql As String = String.Concat("SELECT * FROM ", db.AllTableNames(0))
                    ds = db.ExecuteDataSet(sql)
                Case Else
                    Return
            End Select

            CData.Cache = Nothing 'Read fresh data (unnecessary)

            Dim read As New CDataList(ds.Tables(0).Rows.Count)
            For Each dr As DataRow In ds.Tables(0).Rows
                'Get the date

                Dim x As DateTime
                If hasHeadings Then
                    Try
                        x = CAdoData.GetDate(dr, "Date")
                    Catch
                        Try
                            x = GetDate(CAdoData.GetInt(dr, "Date"))
                        Catch
                            Dim s As String = CAdoData.GetStr(dr, "Date")
                            x = CTextbox.GetDate(s)
                        End Try
                    End Try
                Else
                    Try
                        x = CAdoData.GetDate(dr, 0)
                    Catch
                        Try
                            x = GetDate(CAdoData.GetInt(dr, 0))
                        Catch
                            Dim s As String = CAdoData.GetStr(dr, 0)
                            x = CTextbox.GetDate(s)
                        End Try
                    End Try
                End If

                If DateTime.MinValue = x Then Continue For


                Dim d As CData = Series.Datas.GetByDate(x)
                If IsNothing(d) Then
                    d = read.GetByDate(x)
                    If Not IsNothing(d) Then Continue For
                    d = New CData
                    d.DataSeriesId = Series.SeriesId
                    d.DataDate = x
                End If

        If hasHeadings Then
            d.DataOpen = CAdoData.GetDbl(dr, "Open")
            d.DataHigh = CAdoData.GetDbl(dr, "High")
            d.DataLow = CAdoData.GetDbl(dr, "Low")
            d.DataClose = CAdoData.GetDbl(dr, "Close")
        Else
            d.DataOpen = CAdoData.GetDbl(dr, 1)
            d.DataHigh = CAdoData.GetDbl(dr, 2)
            d.DataLow = CAdoData.GetDbl(dr, 3)
            d.DataClose = CAdoData.GetDbl(dr, 4)
        End If
        read.Add(d)
            Next


            CData.Cache = Nothing 'avoid cache management
            read.SaveAll()
            CData.Cache = Nothing 'unnecessary freshen, recacluate everyting
        End If
    End Sub
    Private Shared Function GetDate(ByVal i As Integer) As DateTime
        Dim yyyy As Integer = Math.Floor(i / 10000)
        i = i - yyyy * 10000
        Dim mm As Integer = Math.Floor(i / 100)
        Dim dd As Integer = i - mm * 100

        Try
            Return New DateTime(yyyy, mm, dd)
        Catch
            Return DateTime.MinValue
        End Try
    End Function

#End Region


End Class
